//
//  SCOCR.m
//  OCRDemo
//
//  Created by 党帅 on 2019/6/4.
//  Copyright © 2019 党帅. All rights reserved.
//

#import "SCOCR.h"

static NSString *kVinApiBaseUrl = @"https://vin.market.alicloudapi.com/api/predict/ocr_vin";
static NSString *kVinAppKey = @"203747504";
static NSString *kVinAppSecret = @"flx4oljpz6kv5ohp20gr1ef9dnej13sl";
static NSString *kVinAppCode = @"aa87ba25460e4ec38a554c046d1417aa";
//static BOOL apiWorking;

@implementation SCOCR

/*
- (instancetype)init {
    self = [super init];
    if (self) {
        [self startTesseract];
    }
    return self;
}

- (void)startTesseract {
    _tesseract = [[G8Tesseract alloc] initWithLanguage:@"eng" engineMode:G8OCREngineModeTesseractCubeCombined];
    _tesseract.pageSegmentationMode = G8PageSegmentationModeAuto;
}


- (void)setDetectorImage:(UIImage *)detectorImage {
    _detectorImage = detectorImage;
    _tesseract.image = detectorImage;
}

- (void)recognizeWithSuccessHandler:(void (^)(NSString *))block {
//    NSLog(@">>>start");
    BOOL finish =  [_tesseract recognize];
    NSString *string = [_tesseract recognizedText];
//    NSLog(@">>>end");
    if (string.length && finish && block) {
        block(string);
    }
}

- (NSString *)recognizeText {
    BOOL finish =  [_tesseract recognize];
    if (finish) {
        NSString *string = [_tesseract recognizedText];
        return string;
    } else {
        return nil;
    }
}
*/

+ (void)aliOcrRecognizeImage:(UIImage *)image completion:(void(^)(NSString *))block {
    if (!image) {
        if ([NSThread isMainThread]) {
            block(nil);
        } else {
            dispatch_sync(dispatch_get_main_queue(), ^{
               block(nil);
            });
        }
        return;
    }
    NSString *image64 = [self encodeToBase64StringFromImage:image];
    NSString *imageBody = [NSString stringWithFormat: @"{\"image\":\"%@\"}",image64];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: kVinApiBaseUrl] cachePolicy:1 timeoutInterval: 5];
    request.HTTPMethod = @"POST";
    [request addValue:[NSString  stringWithFormat:@"APPCODE %@", kVinAppCode]  forHTTPHeaderField:@"Authorization"];
    //根据API的要求，定义相对应的Content-Type
    [request addValue: @"application/json; charset=UTF-8" forHTTPHeaderField: @"Content-Type"];
    NSData *data = [imageBody dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSURLSession *requestSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [requestSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable body, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *vin = nil;
        if (body) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:body options:NSJSONReadingMutableLeaves error:nil];
            vin = result[@"vin"];
        }
        if ([NSThread isMainThread]) {
            block(vin);
        } else {
            dispatch_sync(dispatch_get_main_queue(), ^{
               block(vin);
            });
        }
    }];
    [task resume];
}

+ (NSString*)encodeToBase64StringFromImage:(UIImage *)image {
    
    NSData *data = UIImageJPEGRepresentation(image, 1);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

@end
